import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Radio, DatePicker, Modal } from 'antd'
import { UpOutlined, DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import { addWindow } from '@redux/actions'
import style from '../filingCaseManage/CaseManage.module.less'
import OperateModal from '@components/VideoMeetingList/OperateModal'
import CaseNoRender from '@components/CaseNoRender'
const { confirm } = Modal
const { Item } = Form
// const { Option } = Select

const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns () {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 130,
      render: (v, l) => {
        return <CaseNoRender data={l} />
      }
    },
    {
      title: '申请人',
      dataIndex: 'applicant_name',
      key: 'applicant_name',
      width: 150
    },
    {
      title: '被申请人',
      dataIndex: 'respondent_name',
      key: 'respondent_name',
      width: 150
    },
    {
      title: '开始时间',
      dataIndex: 'begin_datetime',
      key: 'begin_datetime',
      width: 150,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD HH:mm') : ''
      }
    },
    {
      title: '结束时间',
      dataIndex: 'end_datetime',
      key: 'end_datetime',
      width: 150,
      render: v => {
        return v ? moment(v * 1000).format('YYYY-MM-DD HH:mm') : ''
      }
    },
    {
      title: '案件状态',
      dataIndex: 'case_status',
      key: 'case_status',
      width: 140
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 120
    },
    {
      title: '经办人',
      dataIndex: 'processer',
      key: 'processer',
      width: 120
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 120,
      render: (value, line) => {
        const modiable = ['完成', '取消'].indexOf(line.status) === -1
        const cancelable = line.status === '预约'
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.openDetail(line)}>详情</span>
            {
              modiable ? (
                <>
                  <span onClick={() => this.modifyMeeting(line)}>修改</span>
                </>
              ) : null
            }
            {
              cancelable && <span onClick={() => this.delMeeting(line)}>取消预约</span>
            }
          </span>
        )
      }
    }
  ]
  return list
}

class VideoMeetingList extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '全部',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    visible: false,
    modifyData: {}
  }

  formRef = React.createRef()

  // 查看详情
  openDetail (data) {
    this.props.addWindow({ id: `caseMeeting-${data.id}`, title: `视频庭审-${data.caseno_desc}`, componentName: 'VideoMeetingDetail', forceRefresh: true, meta: { id: data.id, caseid: data.caseid } })
  }

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取condition
  getCondition (form) {
    const { status } = this.state
    const condition = []
    if (status !== '全部') {
      condition.push({ k: 'm.use', o: 'in', v: status })
    }
    if (form.caseno_desc) {
      condition.push({ k: 'c.caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
    }
    if (form.applicant_name) {
      condition.push({ K: 'c.applicant_name', o: 'like', v: `%${form.applicant_name}%` })
    }
    if (form.respondent_name) {
      condition.push({ K: 'c.respondent_name', o: 'like', v: `%${form.respondent_name}%` })
    }
    if (form.beginTime) {
      condition.push({ k: 'm.begin_datetime', o: '>=', v: Math.floor(moment(form.beginTime.format('YYYY-MM-DD')).valueOf() / 1000) })
    }
    if (form.endTime) {
      condition.push({ k: 'm.end_datetime', o: '<=', v: Math.floor(moment(form.endTime.format('YYYY-MM-DD') + ' 23:59:59').valueOf() / 1000) })
    }
    return condition
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination } = this.state
    const { current, pageSize } = pagination
    const condition = this.getCondition(form)

    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }
    this.setState({ loading: true })
    this.$get('/api/xapc/meeting', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {}, status } = this.props.meta || {}
    if (status) {
      this.setState({
        status
      })
    }
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  // 修改庭审
  modifyMeeting (d) {
    this.setState({
      modifyData: d,
      visible: true
    })
  }

  // 删除庭审二次确认
  delMeeting (d) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要取消该视频庭审吗？',
      onOk: () => {
        this.delRequest(d.id)
      }
    })
  }

  // 删除庭审请求
  delRequest (id) {
    const hide = message.loading('取消中', 120)
    this.$put(`/api/xapc/meeting/cancel/${id}`)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.getTableData()
      }).catch(e => { hide() })
  }

  // 改变庭审
  changeMeeting (d) {
    const { id } = this.state.modifyData
    d.begin_datetime = Math.floor(d.begin_datetime.valueOf() / 1000)
    d.end_datetime = Math.floor(d.end_datetime.valueOf() / 1000)
    delete d.caseno_desc
    if (id) {
      this.modifyMeetingRequest(id, d)
    } else {
      this.addMeetingRequest(d)
    }
  }

  // 修改庭审请求
  modifyMeetingRequest (id, d) {
    const hide = message.loading('提交中', 120)
    this.$put(`/api/xapc/meeting/${id}`, d)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          visible: false,
          modifyData: {}
        })
        this.getTableData()
      })
      .catch(() => hide())
  }

  // 新增庭审请求
  addMeetingRequest (d) {
    const hide = message.loading('提交中', 120)
    this.$post('/api/xapc/meeting', d)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          visible: false,
          modifyData: {}
        })
        this.getTableData()
      })
      .catch(() => hide())
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <OperateModal visible={this.state.visible} data={this.state.modifyData} hide={() => this.setState({ visible: false, modifyData: {} })} onChange={d => this.changeMeeting(d)} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno_desc'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='申请人' name='applicant_name'>
                    <Input placeholder='请输入申请人' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='被申请人' name='respondent_name'>
                    <Input placeholder='请输入被申请人' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='开始日期' name='beginTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结束日期' name='endTime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={16} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-btns-line']}>
          <Button type='primary' ghost onClick={() => this.setState({ visible: true, modifyData: {} })}>新增视频庭审</Button>
          <div className={style['table-tabs-container']}>
            <Radio.Group value={this.state.status} onChange={v => this.changeStatus(v.target.value)}>
              <Radio.Button value='全部'>全部</Radio.Button>
              <Radio.Button value='开庭'>开庭</Radio.Button>
              <Radio.Button value='合议'>合议</Radio.Button>
              <Radio.Button value='调解'>调解</Radio.Button>
            </Radio.Group>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(VideoMeetingList)
